package com.book.service.impl;

import com.book.entity.Book;
import com.book.entity.Borrow;
import com.book.entity.Users;
import com.book.mapper.BookMapper;
import com.book.mapper.UserMapper;
import com.book.service.BookService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author zzw2000
 * @Date 2022年08月27日 7:41
 * @Description 描述
 */
@Service
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper bookMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public List<Book> getBookList() {
        return bookMapper.bookList();
    }

    @Override
    public void delBook(int id) {
        bookMapper.delBook(id);
    }

    @Override
    public void addBook(String title, String desc, double price) {
        bookMapper.addBook(title, desc, price);
    }

    @Override
    public void borrowBook(int uid, int bid) {
        Integer sid = userMapper.getSidByUid(uid);
        if (Objects.isNull(sid)) return;
        bookMapper.borrowBook(sid, bid);
        bookMapper.updateBook(bid, true);
    }

    @Transactional
    @Override
    public void returnBook(Integer id, Integer bid) {
        bookMapper.returnBook(id);
        bookMapper.updateBook(bid, false);
    }

    @Override
    public List<Borrow> borrowInfo(Users users) {
        int id = users.getId();
        List<Borrow> list = bookMapper.borrowInfo(id);
        if (users.getRole().equals("user")) {
            Integer sid = userMapper.getSidByUid(id);
            list = list.stream().filter(borrow -> borrow.getStudentId().equals(sid)).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public void update(Integer id, String password) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = encoder.encode(password);
        userMapper.update(id,pwd);
    }
}
